/**
 * @author truexin
 * @date   16/04/25
 */

import MuiSlider from "../components/mui/MuiSlider.js";
import PullRefresh from "../components/mui/PullRefresh.js";
import TipNum from "../components/TipNum.js";

(function (lf, r) {
    var RC = r.createClass,
        viewCode = lf.finger.viewCode.property,
        openNativeView = lf.bridgeJs.openNativeView,
        ajax = lf.utils.ajax,
        doAction = lf.bridgeJs.doAction;

    const REGISTER_PAGE = 'property-register-info.html',
        NATIVE = 'native',
        H5 = 'h5';

    var item_list = [
        {
            index: 0,
            tipNum: false,
            bgClass: 'red-bg',
            iconCon: 'icon-qiehuanxiaoqu',
            conText: '切换小区',
            type: NATIVE,
            viewCode: viewCode.choseVillage,
        },
        {
            index: 1,
            tipNum: false,
            bgClass: 'lightblue-bg',
            iconCon: 'news',
            conText: '我要报事',
            type: H5,
            viewCode: viewCode.report,
            url: 'report.html?flag=finger'
        },
        {
            index: 2,
            tipNum: false,
            bgClass: 'orange-bg',
            iconCon: 'register',
            conText: '住户登记',
            type: H5,
            url: REGISTER_PAGE
        },
        {
            index: 3,
            tipNum: true,
            bgClass: 'lightgreen-bg',
            iconCon: 'active',
            conText: '社区活动',
            // prod: lf.prod,  //生产不显示加属性
            type: H5,
            url: 'property-notice.html?type=1',
        },
        {
            index: 4,
            tipNum: false,
            bgClass: 'red-bg',
            iconCon: 'new-active',
            conText: '炫生活',
            type: H5,
            url: lf.snsPrefix + '/sns/index.php?s=/mob/weibo/index.html'
        },

        {
            index: 5,
            tipNum: false,
            bgClass: 'green-bg',
            iconCon: 'intro',
            conText: '小区简介',
            type: H5,
            viewCode: viewCode.introduction,
            url: 'property-intro.html'
        },
        {
            index: 6,
            tipNum: false,
            bgClass: 'yellow-bg',
            iconCon: 'note',
            conText: '物业档案',
            type: H5,
            viewCode: viewCode.needToKnow,
            url: 'property-instructions.html'
        },
        {
            index: 7,
            tipNum: false,
            bgClass: 'blue-bg',
            iconCon: 'fee',
            conText: '物业费用',
            type: H5,
            // prod: lf.prod,  //生产不显示加属性
            url: 'property-fee.html'
        },
        {
            index: 8,
            tipNum: true,
            bgClass: 'lightgreen-bg',
            iconCon: 'icon-dongtai',
            conText: '物业动态',
            // prod: lf.prod,  //生产不显示加属性
            type: H5,
            url: 'property-notice.html?type=4'
        },
        {
            index: 9,
            tipNum: true,
            bgClass: 'orange-bg',
            iconCon: 'icon-zixun',
            conText: '生活资讯',
            type: H5,
            // prod: lf.prod,  //生产不显示加属性
            url: 'property-notice.html?type=6'
        },
        {
            index: 10,
            tipNum: false,
            bgClass: 'lightblue-bg',
            iconCon: 'message',
            conText: '消 息',
            viewCode: viewCode.message,
            type: H5,
            url: 'property-msg.html'
        },
        {
            index: 11,
            tipNum: true,
            bgClass: 'red-bg',
            iconCon: 'notice',
            conText: '通知通告',
            type: H5, //跳h5
            viewCode: viewCode.notification,
            url: 'property-notice.html?type=2'   //测试H5
        },
        {
            index: 12,
            tipNum: false,
            bgClass: 'red-bg',
            iconCon: 'icon-test-paper',
            conText: '问卷调查',
            type: H5, //跳h5
            viewCode: viewCode.notification,
            url: 'property-list-survey.html?type=2'   //测试H5
        },
        {
            index: 13,
            tipNum: false,
            bgClass: 'yellow-bg',
            iconCon: 'icon-telephone',
            conText: '客服电话',
            type: H5, //跳h5
            url: 'property-list-survey.html?type=2'   //测试H5
        },
        {
            index: 14,
            tipNum: false,
            bgClass: 'red-bg',
            iconCon: 'icon-tingchechang',
            conText: '停车费',
            type: H5, //跳h5
            prod: lf.prod,  //生产不显示加属性
            url: 'property-parking.html?type=2'   //测试H5
        },
    ];

    var PropertyBody = RC({
        getInitialState() {
            return ({
                activeNum: '',
                dongtaiNum: '',
                zixunNum: '',
                noticeNum: '',
            })
        },
        setNum(user, noticeType) {
            let me = this,
                buildingId = me.props.buildingId;

            ajax({
                data: {
                    userId: user.id,//用户id【如果是业主，则对应t_proprietor表的id；住户，则对应t_resident表的id】
                    groupId: buildingId,  //暂时可以随便传//TODO
                    projectId: user.projectId,
                    noticeType: noticeType
                },
                success: function (data) {
                    if (data.code == '200') {
                        let num = data.data;
                        if (noticeType == '1') {
                            me.setState({
                                activeNum: num
                            })
                        }
                        if (noticeType == '4') {
                            me.setState({
                                dongtaiNum: num
                            })
                        }
                        if (noticeType == '6') {
                            me.setState({
                                zixunNum: num
                            })
                        }
                        if (noticeType == '2,3') {
                            me.setState({
                                noticeNum: num
                            })
                        }
                    }
                    else {
                        alert(data.desc);
                    }
                }
            }, lf.finger.api.property.tipNum);
        },
        getNoticeType(user) {
            let me = this;
            $.each(item_list, function (i) {
                if (this.conText == '通知通告') {
                    let noticeType = '2,3';
                    me.setNum(user, noticeType);
                }
                if (this.conText == '物业动态') {
                    let noticeType = '4';
                    me.setNum(user, noticeType);
                }
                if (this.conText == '生活资讯') {
                    let noticeType = '6';
                    me.setNum(user, noticeType);
                }
                if (this.conText == '社区活动') {
                    let noticeType = '1';
                    me.setNum(user, noticeType);
                }
            })
        },

        componentWillMount() {
            let user = this.props.user;
            this.getNoticeType(user);
            lf.appJs.refresh((user)=> {
                sessionStorage.projectId = user.projectId;
                let origin = item_list.slice(0);//备份原数组
                this.props.ready(user, origin);
                this.getNoticeType(user);
            })
        },

        render: function () {
            let item_list = this.props.item_list,
                item2DArray = lf.utils.to2DArray(item_list || [], 4),
                navList = item2DArray.map((array, i)=> {
                    return (
                        <div key={'array' + i} className="flex">
                            {
                                array.map(menu => {
                                    return <NavBtn iconClass={"iconfont" +
                                " " + menu.bgClass + " " + menu.iconCon}
                                                   data={menu} user={this.props.user} numList={this.state}
                                                   phone={this.props.phone}/>
                                })
                            }
                        </div>
                    )
                })
            return (
                <div className="flex-box">
                    {navList}
                </div>
            )
        }
    })

    var NavBtn = RC({
        clickFn: function () {
            var data = this.props.data,
                viewCode = data.viewCode,
                type = data.type,
                url = data.url,
                text = data.conText,
                env = lf.utils.getEnv(),
                systemFlag = lf.utils.getSys(),
                projectId = this.props.user.projectId,
                ua = navigator.userAgent;

            //TODO 兼容低版本生产 ios, 这个版本没有getUser,所以必须跳 native
            if (env == 'app' && systemFlag == 'IOS' && ua.indexOf('Version') == -1) {
                openNativeView(viewCode);
            }
            else {
                if (type == NATIVE) {
                    openNativeView(viewCode);
                }
                else if (text == '客服电话') {
                    lf.bridgeJs.dial(this.props.phone);
                }
                else if (type == H5 && url.indexOf(lf.snsPrefix) > -1) {
                    url = url + '&project_id=' + sessionStorage.projectId;
                    doAction(url, text);
                }
                else if (type == H5) {
                    doAction(url, text);
                }
                else {
                    return;
                }
            }
        },
        componentDidMount: function () {
            r.findDOMNode(this.refs.btn).addEventListener('tap', function () {
                this.clickFn();
            }.bind(this))
        },
        render: function () {
            var iconClass = this.props.iconClass,
                data = this.props.data;

            let numList = this.props.numList,
                num = '';

            if (data.conText == '社区活动') {
                num = numList.activeNum;
            }
            else if (data.conText == '物业动态') {
                num = numList.dongtaiNum;
            }
            else if (data.conText == '生活资讯') {
                num = numList.zixunNum;
            }
            else if (data.conText == '通知通告') {
                num = numList.noticeNum;
            }
            return (
                <div className="nav-btn" href="javascript:void(0);" ref="btn">
                    <div className="child">
                        <div className="glyph">
                            {
                                data.tipNum ? <TipNum num={num}/> : null
                            }
                            <div className="icon-bg"><i className={iconClass}></i></div>
                            <span>{data.conText}</span>
                        </div>
                    </div>
                </div>
            )
        }
    });

    var Container = RC({
        getInitialState: function () {
            return {
                homeImages: [], //图片相关属性
                imgOpenUrl: [],
                imageContentIds: [],
                richText: '', //富文本
                item_list: [],
                buildingId: '',
                phone: '',
                user: {},
            }
        },
        resetItemList(user, origin) {
            let me = this;
            ajax({
                type: 'POST',
                data: {
                    proprietorId: user.id,
                    userId: user.userId,
                    projectId: user.projectId,
                    houseId: user.houseId,
                },
                success: function (data) {
                    $.each(origin, function (i) {
                        if (this.prod) {
                            origin.splice(i, 1);
                        }
                        if (data.code.indexOf('_MODIFY') > -1 || data.code.indexOf('_CHECK') > -1) {
                            if (this.url == REGISTER_PAGE) {
                                console.log('this is 业主！');
                            }
                        } else {
                            if (this.url == REGISTER_PAGE) {
                                origin.splice(i, 1);
                                console.log('this is not 业主！');
                            }
                        }
                    });
                    me.setState({
                        item_list: origin
                    })
                }
            }, lf.finger.api.household.checkProprietorStatus);
        },
        getHouseList(user, origin){
            ajax({
                type: "GET",
                data: {
                    globalId: user.globalId,
                },
                success: function (data) {
                    if (data.code == '200') {
                        var data = data.dataList;
                        if (data.length > 1) {
                            console.log('该用户存在多套房子');
                        } else {
                            origin.map((info, i)=> {
                                if (info.viewCode == viewCode.choseVillage) {
                                    origin.splice(i, 1);
                                    console.log('这是只有一个房子！');
                                }
                            })
                        }
                    }
                    else {
                        alert(data.desc);
                    }
                }
            }, lf.finger.api.household.getHouseList);
        },
        getBuildingId(user) {
            let me = this;
            ajax({
                type: "GET",
                data: {
                    houseId: user.houseId,
                },
                success: function (data) {
                    if (data.code == '200') {
                        var data = data.data;
                        me.setState({
                            buildingId: data.buildingId
                        })
                    }
                    else {
                        alert(data.desc);
                    }
                }
            }, lf.finger.api.household.getHouseInfo);
        },
        getProjectPhone(user) {
            let me = this;
            ajax({
                data: {
                    projectId: user.projectId,
                },
                success: (data) => {
                    me.setState({
                        phone: data.data.tel,
                    })
                }
            }, lf.finger.api.property.getPhone);
        },
        getHomeImg(user){
            var me = this;
            ajax({
                data: {
                    projectId: user.projectId,
                },
                success: function (data) {
                    var images = [],
                        url = [],
                        imageContentIds = [],
                        titles = [];

                    $.each(data.dataList, function () {
                        if (this.imagePosition && this.imagePosition == '2') {
                            images.push(this.imageUrl);
                            url.push(this.openUrl || '');
                            titles.push(this.title);
                            this.imageContent ? imageContentIds.push(this.id) : imageContentIds.push('');
                        }
                    });
                    me.setState({
                        homeImages: images,
                        imgOpenUrl: url,
                        imageContentIds: imageContentIds,
                        titles: titles,
                    });

                }
            }, lf.finger.api.homeImages);
        },
        componentWillMount: function () {
            let origin = item_list.slice(0),//备份原数组
                me = this,
                user = me.props.user;
            me.setState({
                user: user,
            })
            me.ready(user, origin);
        },
        ready(user, origin){
            let me = this;
            if (!user.custLoginVo) {
                origin.map((info, i)=> {
                    if (info.viewCode == viewCode.choseVillage) {
                        origin.splice(i, 1);
                        console.log('旧版本用户！');
                    }
                });
            }
            me.getBuildingId(user);
            me.getHouseList(user, origin);
            me.getProjectPhone(user);
            me.getHomeImg(user);
            me.resetItemList(user, origin);
        },
        _homeImagesFn: function (node) {
            var $links = $(node).find('.mui-slider-item').not('.mui-slider-item-duplicate'),
                me = this;

            $links.each(function (i) {
                var $me = $(this);
                $me.off();
                $me.on('tap', function () {
                    var id = me.state.imageContentIds[i],
                        url = me.state.imgOpenUrl[i],
                        title = me.state.titles[i];
                    if (id)
                        doAction('property-img-content.html?id=' + id, title);
                    else
                        doAction(url, title);
                });
            });
        },

        render: function () {
            return (
                <div className="property">
                    <MuiSlider height="2.1" imgList={this.state.homeImages} fn={this._homeImagesFn}
                               indicator="true" autoPlay='true' loop={true}/>
                    <div className="main margin-top" ref="native-box">
                        <PropertyBody user={this.state.user} item_list={this.state.item_list}
                                      buildingId={this.state.buildingId} phone={this.state.phone} ready={this.ready}/>
                    </div>
                </div>
            )
        }
    });

    lf.bridgeJs.getUser(function (user) {
        sessionStorage.projectId = user.projectId;
        r.render(
            <PullRefresh data={<Container user={user}/>}/>,
            document.getElementById('root'), function () {
                $('.mui-scroll').css({background: '#fff'});
            }
        )
    })
})(liefeng, React);